package com.zw.yzk.kabu.data.repository;


import com.zw.yzk.kabu.data.network.task.Task;
import com.zw.yzk.kabu.data.cache.store.ExhibitionStore;
import com.zw.yzk.kabu.data.constant.Constant;
import com.zw.yzk.kabu.data.network.ServiceGenerator;
import com.zw.yzk.kabu.data.network.entity.ExhibitionListEntity;
import com.zw.yzk.kabu.data.network.service.ExhibitionListService;
import com.zw.yzk.kabu.data.network.task.ExhibitionListTask;

import javax.inject.Inject;

import rx.Observable;
import rx.functions.Func1;

/**
 * Created by zhanwei on 2017/1/4.
 */

public class ExhibitionListRepository extends CommonRepository {

    @Inject
    ExhibitionStore exhibitionStore;
    private boolean refresh;
    private int totalCount;

    @Inject
    public ExhibitionListRepository() {
        totalCount = ExhibitionListTask.DEFAULT_FAME_COUNT_PER_PAGE;
    }

    @Override
    protected Observable commonObserve(Task task) {
        return ((ExhibitionListTask) task).getLocal ? Observable.just(exhibitionStore.getExhibitionList()) : super.commonObserve(task);
    }

    @Override
    protected Observable connectServer(Task task) {
        ExhibitionListService exhibitionListService = ServiceGenerator.createService(ExhibitionListService.class);
        ExhibitionListTask cosplayListTask = (ExhibitionListTask) task;

        refresh = cosplayListTask.start == 0;
        if (cosplayListTask.start >= totalCount && totalCount != 0) {
            ExhibitionListEntity entity = new ExhibitionListEntity();
            //已经全部加载，直接返回空列表
            entity.errCode = Constant.RESULT_OK;
            entity.result.totalRows = totalCount;

            return Observable.just(entity);
        } else {
            //加载网络数据
            return exhibitionListService.getExhibitionList(
                    cosplayListTask.start,
                    cosplayListTask.size,
                    cosplayListTask.city,
                    cosplayListTask.startTime,
                    cosplayListTask.userId,
                    cosplayListTask.accessToken);
        }

    }

    @Override
    protected Func1<ExhibitionListEntity, Observable> getServerData() {
        return new Func1<ExhibitionListEntity, Observable>() {
            @Override
            public Observable call(ExhibitionListEntity entity) {
                totalCount = entity.result.totalRows;
                saveCosList(refresh, entity);
                return Observable.just(entity);
            }
        };
    }

    /**
     * 保存本地列表
     *
     * @param refresh 是否是属于刷新操作
     * @param entity  cos列表
     */
    private void saveCosList(boolean refresh, ExhibitionListEntity entity) {
        if (refresh) {
            //是刷新操作，需要刷新数据库
            exhibitionStore.refreshExhibitionList(entity);
        } else {
            //不是刷新操作，直接添加数据到数据库
            exhibitionStore.addExhibitionList(entity);
        }
    }
}
